package com.lemon.exam.repository;

import com.lemon.exam.entity.po.PaperAnswerPO;
import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.r2dbc.repository.R2dbcRepository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;


/**
 * 试卷-答案表 数据访问接口
 *
 * @author Lemon
 * @since 2025/05/17 10:51:17
 */
public interface PaperAnswerRepository extends R2dbcRepository<PaperAnswerPO, Long> {
    @Query("""
            SELECT
                total_score, answer, passed, question_score
            FROM biz_paper_answer
            WHERE paper_id = :paperId AND user_id = :userId
            """)
    Mono<PaperAnswerPO> findPaperByPaperIdAndUserId(Long paperId, Long userId);

    Mono<Boolean> existsByPaperIdAndUserId(Long paperId, Long userId);

    @Query("""
            SELECT
            	id, user_id, answer, question_score, total_score, passed
            FROM
            	biz_paper_answer
            WHERE
                CASE
            		WHEN :answerId IS NULL THEN (paper_id = :paperId AND passed IS NULL)
            		ELSE id = :answerId
                END
            	LIMIT 1
            """)
    Mono<PaperAnswerPO> findAnswerByPaperId(Long paperId, Long answerId);

    @Query("SELECT COUNT(1) FROM biz_paper_answer WHERE paper_id = :paperId AND passed IS NULL")
    Mono<Integer> findCountByPaperId(Long paperId);

    @Query("SELECT id, user_id, submit_time, total_score, passed FROM biz_paper_answer WHERE paper_id = :paperId ORDER BY submit_time")
    Flux<PaperAnswerPO> findPaperAnswerByPaperId(Long paperId);
}
